// src/composables/useLogin.ts
import { ref, reactive, onMounted } from 'vue'
import { router } from '@/router/index'
import { getDeviceType } from '@/utils/device'
import authService from '@/auth/auth.service'
import { useAuthStore } from '@/stores/auth'

export interface LoginForm {
  username: string
  password: string
}

export function useLogin() {
  const authStore = useAuthStore()
  const { user } = authStore

  const loginForm = reactive<LoginForm>({
    username: '',
    password: '',
  })

  const errorMsg = ref('')
  const isFormValid = ref(false)
  const isLoading = ref(false)

  // 输入验证
  const validateInput = () => {
    isFormValid.value = loginForm.username.trim() !== '' && loginForm.password.trim() !== ''
    if (isFormValid.value) {
      errorMsg.value = ''
    }
  }

  // 错误提示
  const errorMessage = (text: string) => {
    errorMsg.value = text
    setTimeout(() => {
      errorMsg.value = ''
    }, 3000)
  }

  // 登录处理
  const handleLogin = async () => {
    // 防止XSS攻击
    const xssPattern = /(~|\{|\}|"|'|<|>|\?)/g
    if (xssPattern.test(loginForm.username) || xssPattern.test(loginForm.password)) {
      errorMessage('警告:输入内容包含非法字符')
      return
    }

    try {
      isLoading.value = true
      const safeUsername = encodeURIComponent(loginForm.username)
      const safePassword = encodeURIComponent(loginForm.password)

      await authService.login(safeUsername, safePassword)
      await authStore.initUser()
      router.push('/category')
    } catch (error) {
      console.error('登录失败:', error)
      errorMessage('登录失败，请稍后重试')
    } finally {
      isLoading.value = false
    }
  }

  onMounted(() => {
    validateInput()
    console.log('设备类型:', getDeviceType())
  })

  return {
    user,
    loginForm,
    errorMsg,
    isFormValid,
    isLoading,
    validateInput,
    handleLogin,
    errorMessage,
  }
}
